package com.gaojun;

import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.swing.filechooser.FileSystemView;

import com.gaojun.tool.ConvertVideo;
import com.gaojun.tool.Video;

import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Line;
import javafx.scene.text.Font;
import javafx.stage.DirectoryChooser;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javafx.stage.StageStyle;

/**
 * 合并视频
 * 
 * @author gj
 *
 */
public class MergeVideo extends Stage {
	private double xOffset = 0;
	private double yOffset = 0;
	private TableView<Video> table = new TableView<>();
	private ObservableList<Video> data = FXCollections.observableArrayList();
	private Video selectItem = null;

	public MergeVideo() {
		// TODO Auto-generated constructor stub
		String style = "-fx-background-color:#00000000";
		String styleEntered = "-fx-background-color:#802a2a";
		Pane pane = new Pane();
		pane.setPrefSize(800, 500);
		pane.setStyle("-fx-background-color:#292421");
		Button btnClose = new Button("");
		btnClose.setGraphic(new ImageView(new Image("res/image/stage/closestage.png")));
		btnClose.setLayoutX(760);
		btnClose.setLayoutY(2);
		btnClose.setStyle(style);
		btnClose.setOnMouseEntered(e -> {
			btnClose.setStyle(styleEntered);
		});

		btnClose.setOnMouseExited(e -> {
			btnClose.setStyle(style);
		});

		btnClose.setOnMouseClicked(e -> {
			this.close();
		});
		Button btnHide = new Button("");
		btnHide.setGraphic(new ImageView(new Image("res/image/stage/hide.png")));
		btnHide.setLayoutX(730);
		btnHide.setLayoutY(2);
		btnHide.setStyle(style);
		btnHide.setOnMouseEntered(e -> {
			btnHide.setStyle(styleEntered);
		});

		btnHide.setOnMouseExited(e -> {
			btnHide.setStyle(style);
		});

		btnHide.setOnMouseClicked(e -> {
			this.setIconified(true);
		});

		Button btnHome = new Button("");
		btnHome.setGraphic(new ImageView(new Image("res/image/stage/home.png")));
		btnHome.setLayoutX(700);
		btnHome.setLayoutY(2);
		btnHome.setStyle(style);
		btnHome.setOnMouseEntered(e -> {
			btnHome.setStyle(styleEntered);
		});

		btnHome.setOnMouseExited(e -> {
			btnHome.setStyle(style);
		});

		btnHome.setOnMouseClicked(e -> {
			MultimediaProcessingMain main = new MultimediaProcessingMain();
			try {
				main.start(new Stage());
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			this.close();
		});

		Line line = new Line();
		line.setStartX(0);
		line.setStartY(30);
		line.setEndX(800);
		line.setEndY(30);
		line.setFill(Color.WHITE);
		line.setStroke(Color.WHITE);
		line.setStrokeWidth(0.2);

		BorderPane borderPane = new BorderPane();
		borderPane.setPrefSize(800, 467);
		borderPane.setLayoutX(0);
		borderPane.setLayoutY(31);
		buildBorderPane(borderPane);

		pane.getChildren().add(btnClose);
		pane.getChildren().add(btnHide);
		pane.getChildren().add(line);
		pane.getChildren().add(btnHome);
		pane.getChildren().add(borderPane);

		Scene scene = new Scene(pane);

		// 窗口拖动
		this.addEventHandler(MouseEvent.ANY, new EventHandler<MouseEvent>() {

			@Override
			public void handle(MouseEvent event) {
				// TODO Auto-generated method stub
				event.consume();
				if (event.getEventType() == MouseEvent.MOUSE_PRESSED) {
					xOffset = event.getSceneX();
					yOffset = event.getSceneY();
				} else if (event.getEventType() == MouseEvent.MOUSE_DRAGGED) {
					MergeVideo.this.setX(event.getScreenX() - xOffset);
					if (event.getScreenY() - yOffset < 0) {
						MergeVideo.this.setY(0);
					} else {
						MergeVideo.this.setY(event.getScreenY() - yOffset);
					}
				}
			}
		});
		this.setScene(scene);
		this.initStyle(StageStyle.UNDECORATED);// 设定窗口无边框
		this.getIcons().add(new Image("res/image/stage/logo.png"));
	}

	private void buildBorderPane(BorderPane borderPane) {
		// TODO Auto-generated method stub
		String btnStyle = "-fx-background-color:#808a87";
		String btnSelectStyle = "-fx-background-color:#87ceeb";
		Pane paneCenter = new Pane();
		paneCenter.setPrefSize(800, 377);
		table.setPrefSize(800, 377);
		table.getStylesheets().add(getClass().getResource("table.css").toExternalForm());

		TableColumn videoNameCol = new TableColumn("文件名");
		videoNameCol.setMinWidth(300);
		videoNameCol.setCellValueFactory(new PropertyValueFactory<>("videoName"));

		TableColumn pathCol = new TableColumn("文件路径");
		pathCol.setMinWidth(398);
		pathCol.setCellValueFactory(new PropertyValueFactory<>("path"));

		TableColumn oprateCol = new TableColumn("操作");
		oprateCol.setMinWidth(100);
		oprateCol.setCellFactory((col) -> {
			TableCell<Video, String> cell = new TableCell<Video, String>() {
				@Override
				public void updateItem(String item, boolean empty) {
					super.updateItem(item, empty);
					this.setText(null);
					this.setGraphic(null);
					if (!empty) {
						Button delBtn = new Button("移除");
						delBtn.setGraphic(new ImageView(new Image("res/image/changetype/remove.png")));
						delBtn.setStyle("-fx-background-color:#00000000");
						delBtn.setFont(Font.font(16));
						delBtn.setTextFill(Color.RED);
						this.setGraphic(delBtn);
						delBtn.setOnMouseClicked((me) -> {
							Video video = this.getTableView().getItems().get(this.getIndex());
							data.remove(video);
							System.out.println("删除 " + video.getVideoName() + " 的记录");
						});
					}
				}

			};
			return cell;
		});

		table.setItems(data);
		table.getColumns().addAll(videoNameCol, pathCol, oprateCol);
		table.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<Video>() {
			@Override
			public void changed(ObservableValue<? extends Video> observableValue, Video oldItem, Video newItem) {
				// TODO Auto-generated method stub
				if (newItem != null) {
					selectItem = newItem;
				}
			}
		});

		paneCenter.getChildren().add(table);

		Pane paneBottom = new Pane();
		paneBottom.setPrefSize(800, 90);
		paneBottom.setStyle("-fx-border-width:1 0 0 0;-fx-border-color:#fff");
		Label lblPath = new Label("文件输出位置：");
		lblPath.setTextFill(Color.WHITE);
		lblPath.setFont(Font.font(18));
		lblPath.setLayoutX(10);
		lblPath.setLayoutY(10);

		TextField txtPath = new TextField();
		txtPath.setFont(Font.font(16));
		txtPath.setPrefSize(220, 35);
		txtPath.setLayoutX(10);
		txtPath.setLayoutY(38);
		FileSystemView fsv = FileSystemView.getFileSystemView();
		File com = fsv.getHomeDirectory();
		txtPath.setText(com.getPath());

		Button btnSet = new Button("设置");
		btnSet.setFont(Font.font(16));
		btnSet.setTextFill(Color.WHITE);
		btnSet.setStyle("-fx-background-color:#808a87");
		btnSet.setLayoutX(240);
		btnSet.setLayoutY(38);
		btnSet.setOnAction(e -> {
			DirectoryChooser directoryChooser = new DirectoryChooser();
			File file = directoryChooser.showDialog(this);
			if (file != null) {
				txtPath.setText(file.getPath().toString());
			}

		});

		Button btnView = new Button("浏览");
		btnView.setFont(Font.font(16));
		btnView.setTextFill(Color.WHITE);
		btnView.setStyle("-fx-background-color:#808a87");
		btnView.setLayoutX(300);
		btnView.setLayoutY(38);
		btnView.setOnAction(e -> {
			try {
				Desktop.getDesktop().open(new File(txtPath.getText().toString()));
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		});
		String style = "-fx-background-color:#00000000;-fx-border-color:#f96501;-fx-border-width:1px";
		String enterStyle = "-fx-background-color:f96501;-fx-border-color:#f96501;-fx-border-width:1px;";
		Button btnAdd = new Button("添加文件");
		btnAdd.setGraphic(new ImageView(new Image("res/image/changetype/add.png")));
		btnAdd.setTextFill(Color.WHITE);
		btnAdd.setFont(Font.font(20));
		btnAdd.setLayoutX(470);
		btnAdd.setLayoutY(30);
		btnAdd.setStyle(style);

		btnAdd.setOnMouseEntered(e -> {
			btnAdd.setGraphic(new ImageView(new Image("res/image/changetype/add1.png")));
			btnAdd.setTextFill(Color.BLACK);
			btnAdd.setStyle(enterStyle);
		});

		btnAdd.setOnMouseExited(e -> {
			btnAdd.setGraphic(new ImageView(new Image("res/image/changetype/add.png")));
			btnAdd.setTextFill(Color.WHITE);
			btnAdd.setStyle(style);
		});

		Button btnBegin = new Button("开始转换");
		btnBegin.setGraphic(new ImageView(new Image("res/image/changetype/begin.png")));
		btnBegin.setFont(Font.font(20));
		btnBegin.setTextFill(Color.WHITE);
		btnBegin.setStyle("-fx-background-color:#808a87");
		btnBegin.setLayoutX(630);
		btnBegin.setLayoutY(30);
		btnBegin.setDisable(true);

		btnAdd.setOnMouseClicked(e -> {
			FileChooser fileChooser = new FileChooser();
			fileChooser.setTitle("选择视频");
			fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("All Video", "*.*"),
					new FileChooser.ExtensionFilter("MP4", "*.mp4"), new FileChooser.ExtensionFilter("AVI", "*.avi"),
					new FileChooser.ExtensionFilter("MOV", "*.mov"), new FileChooser.ExtensionFilter("FLV", "*.flv"));
			File file = fileChooser.showOpenDialog(this);
			if (file != null) {
				Video video = new Video(file.getName().toString(), "合并", file.getPath());
				data.add(video);
				btnBegin.setDisable(false);
			}
		});

		btnBegin.setOnMouseClicked(e -> {
			String fileName=txtPath.getText().toString()+File.separatorChar+System.currentTimeMillis()+"_merge.mp4";
			mergeVideo(fileName);

		});
		paneBottom.getChildren().addAll(lblPath, txtPath, btnSet, btnView, btnAdd, btnBegin);

		borderPane.setBottom(paneBottom);
		borderPane.setCenter(paneCenter);
	}

	//ffmpeg -i "concat:input1.mpg|input2.mpg|input3.mpg" -c copy -movflags +faststart output.mpg
	private boolean mergeVideo(String fileName) {
		// TODO Auto-generated method stub
		
		    StringBuilder str=new StringBuilder("concat:");
		   for(int i=0;i<data.size();i++) {
			   str.append(data.get(i).getPath());
			   str.append("|");
		   }
		    String  result=str.substring(0, str.length()-1);
		    result="\""+result+"\"";
		    System.out.println(result);
	        List<String> commend=new java.util.ArrayList<String>();
	        commend.add(System.getProperty("user.dir")+"\\drive\\ffmpeg.exe");
	        commend.add("-i");
	        commend.add(result);
	        commend.add("-c");
	        commend.add("copy");
	        commend.add(fileName);
	        try {
	            ProcessBuilder builder = new ProcessBuilder();
	            builder.command(commend);
	            builder.start();
	            return true;
	        } catch (Exception e) {
	            e.printStackTrace();
	            return false;
	        }
	}
}
